package rattlesnake.callback.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import rattlesnake.callback.config.constant.CallBackConstant;
import rattlesnake.callback.config.filter.MessageFilter;
import rattlesnake.callback.core.cache.Cache;
import rattlesnake.callback.core.cache.CacheConfiguration;
import rattlesnake.callback.core.cache.CacheManager;
import rattlesnake.callback.util.ClassUtil;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package: rattlesnake.callback.config
 * @Description: 标记给IOC容器管理
 * @author: liuxin
 * @date: 17/4/10 下午2:30
 */
//@Configuration
public class MyBeanConfig {
    private static final Logger logger = LoggerFactory.getLogger(MyBeanConfig.class);

    /**
     * 缓存管理器器，
     * 当第一次进入，会计算hash值，创建一个，根据品类创建一个缓存
     * 当第二次进入，会计算出hash值，查找该品类的缓存，并进行hash校验
     * 根据渠道名称，创建缓存
     *
     * @return
     */
//    @Bean
    public CacheManager cacheManager() {
        CacheManager cacheManager = CacheManager.getInstance();
        List<String> channelNames = ClassUtil.getChannelName(CallBackConstant.CHANNELINFO);
        for (String cacheName : channelNames) {
            CacheConfiguration cacheConfiguration = getConfigure();
            cacheConfiguration.setCacheName(cacheName);
            Cache cache = new Cache(cacheConfiguration);
            cacheManager.putCache(cache);
        }
        return cacheManager;
    }


    /**
     * 注册一个过滤器
     * 根据服务名称过滤
     *
     * @return
     */
//    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setName("MessageCodeFilter");
        MessageFilter messageFilter = new MessageFilter();
        registrationBean.setFilter(messageFilter);
        registrationBean.setOrder(1);
        List<String> urlList = new ArrayList<>();
        List<String> categoryList = ClassUtil.getCategoryURl(CallBackConstant.CATEGORYNAMES);
        for (String categoryUrl : categoryList) {
            urlList.add("/" + categoryUrl + "/*");
            logger.debug("过滤渠道地址:/" + categoryUrl + "/*");
        }
        registrationBean.setUrlPatterns(urlList);
        return registrationBean;
    }

    public static CacheConfiguration getConfigure() {
        CacheConfiguration c = new CacheConfiguration();
        //c.setCacheName("Test1");//设置缓存名字
        //最多存放5个元素
        c.setMaxElementsInMemory(500);//设置缓存元素大小
        //假设5秒不用就过期，这两个时间一般默认选小的一个执行，最长时间是 存活的总时间
        c.setTimeToIdleSeconds(5);//设置5s不用就过期
        //假设最长能存活115秒
        c.setTimeToLiveSeconds(10);
        //6秒 检查一次过期
        c.setDiskExpiryThreadIntervalSeconds(6);
        return c;
    }
}
